<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 13-11-7
 * Time: 下午5:45
 */

class Zip {

    protected $_zip_files = array();

    public function __construct(){

    }

    /**
     * 开始打包
     *
     * @param $dir    需要打包的目录
     * @param $file_name  打包后的名称
     */
    public function create_zip($dir, $file_name = ''){

        $dir = trim($dir, '/');

        $base_name = basename($dir);
        $base_dir = dirname($dir);

        if($file_name == '')
            $save_file_path = $dir . '.zip';
        else
            $save_file_path = $base_dir . '/' . $file_name . '.zip';

        $this->read_dir($dir);

        if(empty($this->_zip_files))
            return false;

        $zip = new ZipArchive();
        $zip->open($save_file_path, ZipArchive::OVERWRITE);

        foreach($this->_zip_files as $f){
            //var_dump($f, str_replace($base_dir, '', $f));exit();
            $zip->addFile($f, $this->utf2gbk(str_replace($base_dir . '/', '', $f)));
        }

        $zip->close();

        return $save_file_path;
    }

    /**
     * 递归读取目录文件
     *
     * @param $dir
     * @return bool
     */
    public function read_dir($dir){
        if(!is_dir($dir))
            return false;

        $fo = opendir($dir);
        while($file = readdir($fo)){
            if($file != '.' && $file != '..'){
                $file_name = $dir . '/' . $file;
                if(is_file($file_name))
                    $this->_zip_files[] = $file_name;
                elseif(is_dir($file_name))
                    $this->read_dir($file_name);
            }
        }
        closedir($fo);
    }

    public function get_zip_files(){
        return $this->_zip_files;
    }


    public function utf2gbk($str)
    {
        if (function_exists('mb_convert_encoding')) {
            $str = mb_convert_encoding($str, 'gbk', 'utf-8');
        } else {
            $str = iconv('utf-8', 'gbk', $str);
        }
        return $str;
    }
} 